<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { cloneDeep } from 'lodash-es';
import { Modal, List, Table, type TableProps } from 'ant-design-vue';
import { deptList } from '#/api/system/dept';
import { userList } from '#/api/system/user';
import type { User } from '#/api/system/user/model';

const props = defineProps<{
  open: boolean;
  preselectedUsers: User[];
}>();

const emit = defineEmits(['update:open', 'confirm']);

const institutions = ref<any[]>([]);
const users = ref<User[]>([]);
const internalSelectedUsers = ref<User[]>([]);
const selectedInstitution = ref<any>(null);
const isLoading = ref(false);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

watch(
  () => props.open,
  async (newVal) => {
    if (newVal) {
      internalSelectedUsers.value = cloneDeep(props.preselectedUsers);
      isLoading.value = true;
      try {
        const depts = await deptList({ deptCategory: '1' });
        if (!props.open) return;
        institutions.value = depts;
        if (institutions.value.length > 0) {
          await handleInstitutionClick(institutions.value[0]);
        }
      } catch (error) {
        console.error("Failed to load initial data:", error);
      } finally {
        isLoading.value = false;
      }
    } else {
      users.value = [];
      selectedInstitution.value = null;
      pagination.current = 1;
      pagination.total = 0;
    }
  },
);

async function fetchUsers(page: number = 1) {
  if (!selectedInstitution.value) return;
  isLoading.value = true;
  try {
    const { rows, total } = await userList({
      deptId: selectedInstitution.value.deptId,
      pageNum: page,
      pageSize: pagination.pageSize,
    });
    const { deptId, deptName } = selectedInstitution.value;
    // 2. 不再映射 id，直接使用 userId 和 nickName
    users.value = rows.map(u => ({
      ...u,
      deptId,
      deptName
    }));
    pagination.current = page;
    pagination.total = total;
  } catch (error) {
    console.error(`Failed to fetch users for dept ${selectedInstitution.value.deptId}:`, error);
    users.value = [];
    pagination.total = 0;
  } finally {
    isLoading.value = false;
  }
}

async function handleInstitutionClick(institution: any) {
  if (selectedInstitution.value?.deptId === institution.deptId) {
    return;
  }
  selectedInstitution.value = institution;
  await fetchUsers(1);
}

function handleTableChange(page: { current?: number }) {
  if (page.current) {
    fetchUsers(page.current);
  }
}

function handleUserSelectChange(_selectedRowKeys: (string | number)[], selectedRows: User[]) {
  const currentPageUserIds = users.value.map((u) => u.userId);
  const otherPageUsers = internalSelectedUsers.value.filter(
    (user) => !currentPageUserIds.includes(user.userId),
  );
  internalSelectedUsers.value = [...otherPageUsers, ...selectedRows];
}

function handleConfirm() {
  emit('confirm', internalSelectedUsers.value);
  emit('update:open', false);
}

function handleCancel() {
  emit('update:open', false);
}

const rowSelection = computed<TableProps['rowSelection']>(() => {
  // 3. selection key 也使用 userId
  const selectedRowKeys = internalSelectedUsers.value.map((u) => u.userId);
  return {
    selectedRowKeys,
    onChange: handleUserSelectChange,
    type: 'checkbox',
  };
});

const userTableColumns = [
  {
    title: '用户名',
    dataIndex: 'nickName',
    key: 'nickName',
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
  },
];
</script>

<template>
  <Modal :open="open" title="选择研究人员" width="800px" @ok="handleConfirm" @cancel="handleCancel">
    <div class="flex h-[500px]">
      <div class="w-1/3 pr-4 border-r overflow-y-auto">
        <List :data-source="institutions" :loading="isLoading && !institutions.length" item-layout="horizontal">
          <template #renderItem="{ item }">
            <List.Item :class="{
              'bg-blue-100': selectedInstitution?.deptId === item.deptId,
              'cursor-pointer hover:bg-gray-100': true,
            }" @click="handleInstitutionClick(item)">
              <List.Item.Meta :title="item.deptName" />
            </List.Item>
          </template>
        </List>
      </div>
      <div class="w-2/3 pl-4">
        <Table :columns="userTableColumns" :data-source="users" :loading="isLoading" :pagination="pagination"
          :row-selection="rowSelection" row-key="userId" size="small" @change="handleTableChange" />
      </div>
    </div>
  </Modal>
</template>
